<script setup>
import { artAddChannelService, artEditChannelService } from '@/api/article'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const form = ref(null)
const formModel = ref({
  id: '',
  name: '',
  alias: ''
})
const rules = {
  name: [
    {
      required: true,
      message: '请输入分类名称',
      trigger: 'blur'
    },
    {
      pattern: /^\S{1,10}$/,
      message: '分类别名必须是1-10位的非空字符',
      trigger: 'blur'
    }
  ],
  alias: [
    {
      required: true,
      message: '请输入分类别名',
      trigger: 'blur'
    },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: '分类别名必须是1-15位的字母或数字',
      trigger: 'blur'
    }
  ]
}
const open = (row) => {
  // 编辑的话，就赋值。添加分类，不赋值
  if (row.id) formModel.value = { ...row }
  console.log(formModel.value)
  dialogVisible.value = true
}
const handleClose = () => {
  formModel.value = {
    id: '',
    name: '',
    alias: ''
  }
  dialogVisible.value = false
}
const onSubmit = async () => {
  await form.value.validate()
  const isEdit = formModel.value.id
  if (isEdit) {
    await artEditChannelService(formModel.value)
    ElMessage.success('编辑成功')
  } else {
    await artAddChannelService(formModel.value)
    ElMessage.success('添加成功')
  }
  emit('success')
  handleClose()
}
defineExpose({
  open
})
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formModel.id ? '编辑分类' : '添加分类'"
    width="500"
    :before-close="handleClose"
  >
    <el-form
      ref="form"
      :model="formModel"
      :rules="rules"
      label-width="100px"
      style="padding-right: 30px"
      autocomplete="off"
    >
      <el-form-item label="分类名称" prop="name">
        <el-input placeholder="请输入分类名称" v-model="formModel.name"></el-input>
      </el-form-item>
      <el-form-item label="分类别名" prop="alias">
        <el-input placeholder="请输入分类别名" v-model="formModel.alias"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
